from rest_framework import serializers


class BaseModelSerializer(serializers.ModelSerializer):
    """
        可使用fields序列化所需字段
        可使用exclude排除不需要的字段
    """
    def __init__(self, *args, **kwargs):
        fields = kwargs.pop('fields', None)
        exclude = kwargs.pop('exclude', None)

        super(BaseModelSerializer, self).__init__(*args, **kwargs)

        if fields is not None:
            # 从默认`self.fields`属性中剔除非`fields`中指定的字段
            allowed = set(fields)
            existing = set(self.fields.keys())
            for field_name in existing - allowed:
                self.fields.pop(field_name)
        if exclude is not None:
            # 从默认`self.fields`属性中剔除非`excluded`中指定的字段
            excluded = set(exclude)
            for field_name in excluded:
                self.fields.pop(field_name)
